package framework_result

import (
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"net/http"
)

var ROk = R{
	Msg:  http.StatusText(http.StatusOK),
	Code: http.StatusOK,
}

type R struct {
	Data interface{} `json:"data"`

	Msg string `json:"msg"`

	Code int `json:"code"`
}

func (r *R) IsOk() bool {
	return r.Code == http.StatusOK
}

func Ok() R {
	return R{
		Msg:  http.StatusText(http.StatusOK),
		Code: http.StatusOK,
	}
}

func Error() R {
	return R{
		Msg:  http.StatusText(http.StatusBadRequest),
		Code: http.StatusBadRequest,
	}
}

func Result(param ...interface{}) {
	c := param[0].(*gin.Context)
	var r R
	if len(param) == 1 {
		r = ROk
	} else {
		switch param[1].(type) {
		case nil:
			r = ROk
		case error:
			r.Code = http.StatusBadRequest
			r.Msg = param[1].(error).Error()
		case *gorm.DB:
			e := param[1].(*gorm.DB).Error
			if e != nil {
				r.Code = http.StatusBadRequest
				r.Msg = e.Error()
			} else {
				r = ROk
			}
		}
	}
	c.JSON(http.StatusOK, r)
}
